package com.example.lenovo.weiyi;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.com.ruanmeng.utils.Params;
import com.receiver.NetReceiver;
import com.yolanda.nohttp.rest.Request;

import java.util.ArrayList;
import java.util.List;


/**
 * 封装公共的方法，被其他activity继承
 *
 * @author Administrator
 */
public class BaseActivity extends FragmentActivity implements
        TextWatcher, View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private final String mPageName = "MainActivity";
    static Context mContext;
    NetReceiver mReceiver = new NetReceiver();
    IntentFilter mFilter = new IntentFilter();
    public Request<String> mRequest;
    public static Activity baseContext;
    private PowerManager.WakeLock wl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);// 去除标头
        /**
         * 网络
         */
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, mFilter);
        baseContext = this;
        //打开和关闭屏幕常亮    MyTag可以随便写,可以写应用名称等
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "MyTag");
//        wl.acquire();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //百度统计
//        StatService.onPause(mContext);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mForegroundActivity = this;
        //百度统计
//        StatService.onResume(mContext);
        //是否常亮
        try {
            if(Params.IsWakeClock==1){
                wl.acquire();
            }else {
                wl.release();
            }
        }catch (Exception o){}
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(mReceiver);
        super.onDestroy();
        if (mRequest != null)
            mRequest.cancel();
    }

    //页面跳转
    public void startActivity(Class c) {
        Intent intent = new Intent(this, c);
        this.startActivity(intent);
        //开启Activity的动画
        this.overridePendingTransition(R.anim.next_in, R.anim.next_out);
    }

    private static BaseActivity mForegroundActivity = null;

    /**
     * 获取当前处于前台的activity
     */
    public static BaseActivity getForegroundActivity() {
        return mForegroundActivity;
    }


    // 隐藏键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {

            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            View v = getCurrentFocus();

            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                    + v.getWidth();
            if (event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }



    /**
     * 退出方法，打开将类放入list中， 退出就直接clear了
     */

    private static List<Activity> listActivity = new ArrayList<Activity>();

    public static void AddActivity(Activity activity) {
        listActivity.add(activity);
    }

    public static void clearActivity() {
        for (int i = 0; i < listActivity.size(); i++) {
            if (listActivity.get(i) != null) {
                listActivity.get(i).finish();
            }

        }
        listActivity.clear();
    }
    private static List<Activity> LoginlistActivity = new ArrayList<Activity>();

    public static void AddLoginActivity(Activity activity) {
        LoginlistActivity.add(activity);
    }

    public static void clearLoginActivity() {
        for (int i = 0; i < LoginlistActivity.size(); i++) {
            if (LoginlistActivity.get(i) != null) {
                LoginlistActivity.get(i).finish();
            }

        }
        LoginlistActivity.clear();
    }
    private static List<Activity> MainlistActivity = new ArrayList<Activity>();

    public static void AddMianActivity(Activity activity) {
        MainlistActivity.add(activity);
    }

    public static void clearMainActivity() {
        for (int i = 0; i < MainlistActivity.size(); i++) {
            if (MainlistActivity.get(i) != null) {
                MainlistActivity.get(i).finish();
            }

        }
        MainlistActivity.clear();
    }

    /**
     * 退出方法，打开将类放入list中， 退出就直接clear了
     */

    private static List<Activity> listPCXQActivity = new ArrayList<Activity>();

    public static void AddPCXQActivity(Activity activity) {
        listPCXQActivity.add(activity);
    }

    public static void clearPCXQActivity() {
        for (int i = 0; i < listPCXQActivity.size(); i++) {
            if (listPCXQActivity.get(i) != null) {
                listPCXQActivity.get(i).finish();
            }

        }
        listPCXQActivity.clear();
    }

    /**
     * laytitle
     */
    //显示返回
    public void ShowLayBack() {
        ((ImageView) findViewById(R.id.imv_lay_back))
                .setVisibility(View.VISIBLE);
    }

    //隐藏返回
    public void HiddenLayBack() {
        ((ImageView) findViewById(R.id.imv_lay_back))
                .setVisibility(View.GONE);
    }
    //显示消息
    public void ShowLayMess() {
        ((ImageView) findViewById(R.id.imv_home))
                .setVisibility(View.VISIBLE);
    }

    //隐藏消息
    public void HiddenLayMess() {
        ((ImageView) findViewById(R.id.imv_home))
                .setVisibility(View.GONE);
    }
    //显示返回
    public void ShowLayNext() {
        ((TextView) findViewById(R.id.tv_lay_next))
                .setVisibility(View.VISIBLE);
    }
    //显示我的订单
    public void ShowLayOrder() {
        ((TextView) findViewById(R.id.tv_lay_myorder))
                .setVisibility(View.VISIBLE);
    }
    //显示新建
    public void ShowLayAdd() {
        ((TextView) findViewById(R.id.tv_lay_add))
                .setVisibility(View.VISIBLE);
    }
    //显示新建
    public void ShowLayService() {
        ((TextView) findViewById(R.id.tv_lay_service))
                .setVisibility(View.VISIBLE);
    }
    //显示新建
    public void ShowLayZiXun() {
        ((TextView) findViewById(R.id.tv_lay_zixun))
                .setVisibility(View.VISIBLE);
    }
    //显示保存
    public void ShowLaySave() {
        ((TextView) findViewById(R.id.tv_lay_save))
                .setVisibility(View.VISIBLE);
    }
    //显示收藏
    public void ShowLayCollection() {
        ((ImageView) findViewById(R.id.imv_collection))
                .setVisibility(View.VISIBLE);
    }

    //隐藏返回
    public void HiddenLayNext() {
        ((TextView) findViewById(R.id.tv_lay_next))
                .setVisibility(View.GONE);
    }


    //返回事件
    public void LayBack() {
        ((ImageView) findViewById(R.id.imv_lay_back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                overridePendingTransition(R.anim.pre_in, R.anim.pre_out);
            }
        });
    }
    //返回事件
    public void LayTitleBack() {
        ((ImageView) findViewById(R.id.imv_laytitle_back)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
                overridePendingTransition(R.anim.pre_in, R.anim.pre_out);
            }
        });
    }

    //标题栏的返回按钮，onclick = "doClick"   该方法不用再每个页面调用
    public void doClick(View v) {
        switch (v.getId()) {
            case R.id.imv_lay_back:
                onBackPressed();
                this.overridePendingTransition(R.anim.pre_in, R.anim.pre_out);//退出或进入某页面的平移动画
                break;
        }
    }

    //修改标题
    public void ChangLayTitle(String title) {
        ((TextView) findViewById(R.id.tv_lay_title))
                .setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.tv_lay_title)).setText(title);
    }



    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    public void onClick(View view) {

    }

    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

    }
    //设置Android app的字体不随系统全局字体大小的变动而变动
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config=new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config,res.getDisplayMetrics() );
        return res;
    }
}
